package com.ns.school.common.filter;

import com.ns.school.common.constant.StaticVar;
import com.ns.school.common.utils.HttpUtil;

import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;

/**
 * 构建可重复读取inputStream的request
 *
 * @author Spark
 */
public class RepeatedlyRequest extends HttpServletRequestWrapper {
    private final byte[] body;

    public RepeatedlyRequest(HttpServletRequest request, ServletResponse response) throws IOException {
        super(request);
        request.setCharacterEncoding(StaticVar.UTF8);
        response.setCharacterEncoding(StaticVar.UTF8);

        body = HttpUtil.getBodyString(request).getBytes(StandardCharsets.UTF_8);
    }

    @Override
    public BufferedReader getReader() throws IOException {
        return new BufferedReader(new InputStreamReader(getInputStream()));
    }

    @Override
    public ServletInputStream getInputStream() throws IOException {
        try (ByteArrayInputStream is = new ByteArrayInputStream(body)) {
            return new ServletInputStream() {
                @Override
                public int read() {
                    return is.read();
                }

                @Override
                public boolean isFinished() {
                    return false;
                }

                @Override
                public boolean isReady() {
                    return false;
                }

                @Override
                public void setReadListener(ReadListener readListener) {
                }
            };
        }
    }
}
